2. Add Two Numbers - LeetCode Solution


Linked List Math

Python Code:

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
        ptr1 = l1
        ptr2 = l2
        
        ans = ListNode()
        
        head = ans
        carry =0 
        
        while l1 or l2:
            
            if l2 and  not l1:
                s = str(l2.val + carry)
     
                if len(s) ==2:
                    
                    a = ListNode(int(s[1]))
                    carry = int(s[0])
                else:
                    a = ListNode(int(s))
                    carry = 0
                
                head.next = a
                head = head.next
                l2 = l2.next
            elif l1 and not l2:
                s = str( l1.val + carry)
            
                if len(s) ==2:
                    
                    a = ListNode(int(s[1]))
                    carry = int(s[0])
                else:
                    a = ListNode(int(s))
                    carry = 0
                
                head.next = a
                head = head.next
                l1 = l1.next
            
            elif l1 and l2:
                s = str(l1.val + l2.val + carry)
                print(s, l1.val, l2.val, carry)
                if len(s) ==2:
                    
                    a = ListNode(int(s[1]))
                    carry = int(s[0])
                else:
                    a = ListNode(int(s))
                    carry = 0
                
                head.next = a
                head = head.next
                l1 = l1.next
                l2 = l2.next
                
        if carry != 0:
                a = ListNode(carry)
                carry = 0
                head.next = a
                head = head.next
            
        return ans.next
                


Comments

Submit
0 Comments
More Questions

1384A - Common Prefixes
371A - K-Periodic Array
1542A - Odd Set
1567B - MEXor Mixup
669A - Little Artem and Presents
691B - s-palindrome
851A - Arpa and a research in Mexican wave
811A - Vladik and Courtesy
1006B - Polycarp's Practice
1422A - Fence
21D - Traveling Graph
1559B - Mocha and Red and Blue
1579C - Ticks
268B - Buttons
898A - Rounding
1372B - Omkar and Last Class of Math
1025D - Recovering BST
439A - Devu the Singer and Churu the Joker
1323A - Even Subset Sum Problem
1095A - Repeating Cipher
630F - Selection of Personnel
630K - Indivisibility
20B - Equation
600B - Queries about less or equal elements
1015A - Points in Segments
1593B - Make it Divisible by 25
680C - Bear and Prime 100
1300A - Non-zero
1475E - Advertising Agency
1345B - Card Constructions